<?php
class Controller_Purchase_Order extends Controller_Abstract
{
	function actionCreate()
	{
		$this->_view['title'] = '采购单创建';
		$user = Purchase_Order::getUser(true);
		$this->_view['user'] = $user['data'];
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
		if (isset($_GET['id']))
		{
			$order = Purchase_Order::find('id=?', $_GET['id'])->asArray()->getOne();
			$order['item'] = Purchase_Order_Item::find('purchase_order_item.purchase_order_id=? and (purchase_order_item.actual_quantity=0 or purchase_order_item.actual_quantity is NULL)', $_GET['id'])
				->joinLeft('product_warehouse', 'product_warehouse.purchase_budget_quantity, product_warehouse.purchase_quantity, product_warehouse.wholesale_quantity, product_warehouse.warning_quantity, product_warehouse.sold_quantity, product_warehouse.actual_quantity, product_warehouse.sales_status, product_warehouse.purchase_status', 'product_warehouse.product_basic_id=purchase_order_item.product_basic_id and product_warehouse.warehouse_id=' . $order['warehouse_id'])
				->joinLeft('product_basic', 'number, name, purchase_price', 'product_basic.id=purchase_order_item.product_basic_id')
				->joinLeft('product_provider', 'name as budget_provider_name', 'product_provider.id=purchase_order_item.budget_provider_id')
				->asArray()->getAll();
			$this->_view['order'] = $order;
		}
		if (isset($_GET['product_warehouse_ids']))
		{
			$product_warehouse_ids = explode(',', $_GET['product_warehouse_ids']);
			$provider = Product_Warehouse::find('product_warehouse.id in (?)', $product_warehouse_ids)
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->joinLeft('product_provider', '', 'product_provider.id=product_basic.preferred_provider_id')
				->distinct('product_provider.id')->setColumns('product_provider.id')->asArray()->getAll();
			$r1 = 'product_warehouse.purchase_status=' . Q::ini('custom_flag/product_purchase_status/restock/value') . ' or product_warehouse.actual_quantity < product_warehouse.sold_quantity';
			$r2 = '(product_warehouse.sales_status in (' . Q::ini('custom_flag/product_sales_status/new_product/value') . ',' . Q::ini('custom_flag/product_sales_status/normal_sales/value') . ') and product_warehouse.actual_quantity<product_warehouse.safe_quantity) or (product_warehouse.sales_status=' . Q::ini('custom_flag/product_sales_status/temporarily_off/value') . ' and product_warehouse.sold_quantity>product_warehouse.actual_quantity)';
			$where = "(($r1) or ($r2))";
			$provider_arr = array();
			foreach ($provider as $p)
			{
				if ($p['id'])
				{
					$provider_arr[] = $p['id'];
				}
			}
			$provider_to_product['item'] = array();
			foreach ($provider_arr as $p)
			{
				$product_warehouse = Product_Warehouse::find($where. ' and product_basic.preferred_provider_id='.$p.' and product_warehouse.warehouse_id='.$_GET['warehouse_id'])
					->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
					->joinLeft('product_provider', '', 'product_provider.id='.$p)
					->setColumns('product_basic.name, product_basic.number, product_basic.purchase_price, product_basic.last_purchase_price as budget_price, product_warehouse.id as product_warehouse_id, product_warehouse.product_basic_id, product_warehouse.warning_quantity, product_warehouse.sold_quantity, product_warehouse.actual_quantity, product_warehouse.purchase_budget_quantity, product_warehouse.purchase_quantity, product_warehouse.wholesale_quantity, product_warehouse.sales_status, product_warehouse.purchase_status, product_warehouse.safe_quantity, product_provider.id as budget_provider_id, product_provider.name as budget_provider_name')
					->asArray()->getAll();
				foreach ($product_warehouse as $pw)
				{
					$provider_to_product['item'][] = $pw;
				}
			}
			$array_unshift_product = array();
			foreach ($provider_to_product['item'] as $key => $p)
			{
				$provider_to_product['item'][$key]['budget_quantity'] = $p['safe_quantity'] - $p['actual_quantity'];
				foreach ($product_warehouse_ids as $pwi)
				{
					if ($p['product_warehouse_id'] == $pwi)
					{
						$array_unshift_product[$key] = $provider_to_product['item'][$key];
						unset($provider_to_product['item'][$key]);
					}
				}
			}
			if ($array_unshift_product)
			{
				foreach ($array_unshift_product as $aup)
				{
					array_unshift($provider_to_product['item'], $aup);
				}
			}
			$r0 = $r1 = array();
			foreach($provider_to_product['item'] as $p)
			{
				$r0[] = $p['number'];
				if ($p['sales_status'] == Q::ini('custom_flag/product_sales_status/temporarily_off/value'))
				{
					$p['sales_status'] = 10;
				}
				$r1[] = $p['sales_status'];
			}
			array_multisort($r1, $r0, $provider_to_product['item']);
			$this->_view['order'] = array('item' => $provider_to_product['item']);
		}
	}
	
	function actionCreateSave()
	{
		$this->_view['title'] = '采购单创建（保存）';
		if ($_POST)
		{
			$item = isset($_POST['item']) ? $_POST['item'] : array();
			$tmp = array();
			foreach ($item as $k => $i)
			{
				if (array_key_exists($i['product_basic_id'], $tmp))
				{
					$item[$tmp[$i['product_basic_id']]]['budget_quantity'] += $i['budget_quantity'];
					unset($item[$k]);
				}
				else
				{
					$tmp[$i['product_basic_id']] = $k;
				}
			}
			$order =array(
				'purchase_user_id' => $_POST['purchase_user_id'],
				'purchase_time' => $_POST['purchase_time'],
				'notes' => $_POST['notes'],
				'payment_type' => $_POST['purchase_order_payment_type'],
				'warehouse_id' => $_POST['warehouse_id'],
				'item' => $item
			);
			$result = Purchase_Order::createOrder($order);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('保存成功', '正在返回..', url('Purchase::Order/OrderList'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('保存失败', '不能生成订单编号', url('Purchase::Order/Create'), $result['ack']);
			}
		}
	}

	function actionDel()
	{
		$this->_view['title'] = '采购单删除（操作）';
		$result = Purchase_Order::del($_GET['id']);
		if ($result['ack'] == SUCCESS)
		{
			return $this->_redirectMessage('删除成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
		}
		else
		{
			return $this->_redirectMessage('删除失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
		}
	}
	
	function actionOrderList()
	{
		$this->_view['title'] = '采购单列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$user = purchase_order::getUser();
		$this->_view['user'] = $user['data'];
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
		$url_arr['limit'] = $user['ack'];
		$url_arr['type'] = Q::ini('custom_flag/purchase_order_type/order/value');
		$result = Purchase_Order::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$purchase_order = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Purchase::Order/OrderList', $url_arr));
			$this->_view['page'] = $page->getPage();
			$this->_view['purchase_order'] = $purchase_order;
			$where = Purchase_Order::buildSearchWhere($url_arr);
			$this->_view['budget_amount'] = QDB::getConn()->execute('select sum(budget_amount) from purchase_order where ' . $where)->fetchOne();
			$this->_view['actual_amount'] = QDB::getConn()->execute('select sum(actual_amount) from purchase_order where ' . $where)->fetchOne();
			$this->_view['actual_quantity'] = QDB::getConn()->execute('select sum(purchase_order_item.actual_quantity) from purchase_order_item left join purchase_order on purchase_order.id=purchase_order_item.purchase_order_id where ' . $where)->fetchOne();
		}
	}
	
	function actionBudgetEdit()
	{
		$this->_view['title'] = '采购单预计修改';
		$id = $_GET['id'];
		if (isset($id))
		{
			$judge_result = Purchase_Order::judgeEditBudget($id);
			if ($judge_result['ack'] == SUCCESS)
			{
				$purchase_order = Purchase_Order::find('purchase_order.id=?', $id)
					->joinLeft('warehouse', 'warehouse.name as warehouse_name', 'warehouse.id=purchase_order.warehouse_id')
					->asArray()->getOne();
				$item = Purchase_Order_Item::find('purchase_order_id =?', $id)
					->joinLeft('product_warehouse', 'purchase_budget_quantity, sold_quantity, safe_quantity, warning_quantity, purchase_quantity, wholesale_quantity, sales_status, purchase_status, actual_quantity', 'product_warehouse.product_basic_id=purchase_order_item.product_basic_id and product_warehouse.warehouse_id=' . $purchase_order['warehouse_id'])
					->joinLeft('product_basic', 'number as product_number, name as product_name, purchase_price', 'product_basic.id = purchase_order_item.product_basic_id')
					->joinLeft('product_provider', 'name as budget_provider_name', 'product_provider.id=purchase_order_item.budget_provider_id')
					->asArray()->getAll();
				$this->_view['item'] = $item;
				$this->_view['purchase_order'] = $purchase_order;
				$user = User::getONdutyUser();
				$this->_view['user'] = $user;
			}
			else
			{
				return $this->_redirectMessage('发生错误', $judge_result['message'], url('Purchase::Order/OrderList'), $judge_result['ack']);
			}
		}
		else
		{
			return $this->_redirect(url('Purchase::Order/OrderList'));
		}
	}
	
	function actionBudgetEditSave()
	{
		$this->_view['title'] = '采购单预计修改（保存）';
		if ($_POST)
		{
			$item = isset($_POST['item']) ? $_POST['item'] : array();
			$tmp = array();
			foreach ($item as $k => $i)
			{
				if (array_key_exists($i['product_basic_id'], $tmp))
				{
					$item[$tmp[$i['product_basic_id']]]['budget_quantity'] += $i['budget_quantity'];
					unset($item[$k]);
				}
				else
				{
					$tmp[$i['product_basic_id']] = $k;
				}
			}
			$order = array(
				'id' => $_POST['id'],
				'purchase_user_id' => $_POST['purchase_user_id'],
				'purchase_time' => $_POST['purchase_time'],
				'notes' => $_POST['notes'],
				'payment_type' => $_POST['purchase_order_payment_type'],
				'item' => $item
			);
			$result = Purchase_Order::editBudget($order);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('修改成功', '返回列表', $_POST['history'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('采购单不允许修改', '返回列表', $_POST['history'], $result['ack']);
			}			
		}
	}
	
	function actionAuditList()
	{
		$this->_view['title'] = '采购单审核列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$user = purchase_order::getUser();
		$this->_view['user'] = $user['data'];
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
		$url_arr = Helper_BSS_Normal::buildCondition();
		$url_arr['type'] = Q::ini('custom_flag/purchase_order_type/order/value');
		$url_arr['purchase_order_status'][Q::ini('custom_flag/purchase_order_status/new/value')] = Q::ini('custom_flag/purchase_order_status/new/value');
		$result = Purchase_Order::Search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$purchase_order = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Purchase::Order/AuditList', $url_arr));
			$this->_view['page'] = $page->getPage();
			$this->_view['purchase_order'] = $purchase_order;
		}
	}
	
	function actionAudit()
	{
		$this->_view['title'] = '采购单审核（操作）';
		if (isset($_GET['ids']))
		{
			$purchase_order_ids = explode(',', $_GET['ids']);
			$message = array();
			foreach ($purchase_order_ids as $id)
			{
				$result = Purchase_Order::auditPurchase($id);
				if ($result['ack'] == FAILURE)
				{
					$message[] = $result['message'];
				}
			}
			if ($message)
			{
				return $this->_redirectMessage('审核部分失败', implode("\n", $message), url('Purchase::Order/AuditList'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('审核成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
		else
		{
			return $this->_redirect(url('Purchase::Order/AuditList'));
		}
	}
	
	function actionActualEdit()
	{
		$this->_view['title'] = '采购单实际修改';
		$id = $_GET['id'];
		if (isset($id))
		{
			$judge_result = Purchase_Order::judgeEditActual($id);
			if ($judge_result['ack'] == SUCCESS)
			{
				$purchase_order = Purchase_Order::find('purchase_order.id =?', $id)
					->joinLeft('user', 'name as purchase_user_name', 'user.id = purchase_order.purchase_user_id')
					->joinLeft('warehouse', 'warehouse.name as warehouse_name', 'warehouse.id=purchase_order.warehouse_id')
					->asArray()->getOne();
				$item = Purchase_Order_Item::find('purchase_order_item.purchase_order_id =?', $id)
					->joinLeft('product_warehouse', 'sold_quantity, safe_quantity, warning_quantity, actual_quantity as stock_quantity', 'product_warehouse.product_basic_id=purchase_order_item.product_basic_id and product_warehouse.warehouse_id=' . $purchase_order['warehouse_id'])
					->joinLeft('product_basic', 'number as product_number, name as product_name', 'product_basic.id = purchase_order_item.product_basic_id')
					->joinLeft('product_provider as a', 'name as budget_provider_name', 'a.id = purchase_order_item.budget_provider_id')
					->joinLeft('product_provider as b', 'name as actual_provider_name', 'b.id = purchase_order_item.actual_provider_id')
					->asArray()->getAll();
				$this->_view['purchase_order'] = $purchase_order;
				$this->_view['item'] = $item;
			}
			else
			{
				return $this->_redirectMessage('发生错误', $judge_result['message'], url('Purchase::Order/OrderList'), $judge_result['ack']);
			}
		}
		else
		{
			return $this->_redirect(url('Purchase::Order/OrderList'));
		}
	}
	
	function actionActualEditSave()
	{
		$this->_view['title'] = '采购单实际修改(保存)';
		if (isset($_POST['item']) && isset($_POST['id']))
		{
			$order = array(
				'id' => $_POST['id'],
				'item' => array(),
				'purchase_hold_flag' => Q::ini('custom_flag/purchase_hold_flag/unhold/value')
			);
			$message = array();
			foreach ($_POST['item'] as $k => $p)
			{
				$check_in_db = Purchase_Order_Item::find('purchase_order_item.id=? and purchase_order_item.purchase_order_id=?', $k, $_POST['id'])
					->joinLeft('product_basic', 'number as product_number', 'product_basic.id=purchase_order_item.product_basic_id')
					->asArray()->getOne();
				if ($check_in_db)
				{
					if (isset($p['actual_quantity']))
					{
						$order['item'][$k]['actual_quantity'] = (trim($p['actual_quantity']) == '') ? $check_in_db['budget_quantity'] : (int)$p['actual_quantity'];
					}
					else
					{
						$message[] = $check_in_db['product_number'] . '：传参有误（缺失实际数参数）！';
					}
					if (isset($p['actual_price']))
					{
						if ((float)$p['actual_price'] > (float)$check_in_db['budget_price'])
						{
							$order['purchase_hold_flag'] = Q::ini('custom_flag/purchase_hold_flag/holded/value');
						}
						$order['item'][$k]['actual_price'] = empty(trim($p['actual_price'])) ? $check_in_db['budget_price'] : (float)$p['actual_price'];
					}
					else
					{
						$message[] = $check_in_db['product_number'] . '：传参有误（缺失实际价格）！';
					}
					if (isset($p['actual_provider_id']))
					{
						$order['item'][$k]['actual_provider_id'] = empty(trim($p['actual_provider_id'])) ? $check_in_db['budget_provider_id'] : (int)$p['actual_provider_id'];
					}
					else
					{
						$message[] = $check_in_db['product_number'] . '：传参有误（缺失实际供应商ID）！';
					}
					if (isset($p['notes']))
					{
						$order['item'][$k]['notes'] = trim($p['notes']);
					}
					else
					{
						$message[] = $check_in_db['product_number'] . '：传参有误（缺失备注）！';
					}
				}
			}
			if ($message)
			{
				return $this->_redirectMessage('保存失败', implode("\n", $message), $_SERVER['HTTP_REFERER'], FAILURE);
			}
			else
			{
				$result = Purchase_Order::editActual($order);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('保存成功', '返回列表', $_POST['history'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('保存失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			
		}
		else
		{
			return $this->_redirectMessage('保存失败', '提交方式或参数有误！', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionDetail()
	{
		$this->_view['title'] = '详细';
		$url_arr = Helper_BSS_Normal::buildCondition();
		if ($url_arr)
		{
			$purchase_order = Purchase_Order::find('purchase_order.id =?', $url_arr['id'])
				->joinLeft('user', 'name as purchase_user_name', 'user.id = purchase_order.purchase_user_id')
				->joinLeft('warehouse', 'warehouse.name as warehouse_name', 'warehouse.id=purchase_order.warehouse_id')
				->asArray()->getOne();
			$item = Purchase_Order_Item::find('purchase_order_item.purchase_order_id =?', $url_arr['id'])
				->joinLeft('product_basic', 'number as product_number, name, purchase_price', 'product_basic.id = purchase_order_item.product_basic_id')
				->joinLeft('product_warehouse', 'product_warehouse.purchase_budget_quantity, product_warehouse.purchase_quantity, product_warehouse.wholesale_quantity, product_warehouse.purchase_status, product_warehouse.sales_status, product_warehouse.actual_quantity as stock_quantity, product_warehouse.sold_quantity, product_warehouse.safe_quantity, product_warehouse.warning_quantity', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $purchase_order['warehouse_id'])
				->joinLeft('product_provider as a', 'name as budget_provider_name', 'a.id = purchase_order_item.budget_provider_id')
				->joinLeft('product_provider as b', 'name as actual_provider_name', 'b.id = purchase_order_item.actual_provider_id')
				->asArray()->getAll();
			Helper_BSS_Normal::getProductImgUrl($item, 'product_number');
			$this->_view['purchase_order'] = $purchase_order;
			$this->_view['item'] = $item;
		}
		else
		{
			return $this->_redirect(url('Purchase::Order/OrderList'));
		}
	}
	
	function actionProductInfoAjax()
	{
		$this->_view['title'] = '产品信息请求ajax';
		$warehouse_id = isset($_REQUEST['warehouse_id']) ? $_REQUEST['warehouse_id'] : Warehouse::getDefaultWarehouseId(); 
		$product_basic = Product_Warehouse::search(array('number_or_name' => $_REQUEST['q'], 'warehouse_id' => $warehouse_id), 0, 10);
		$result = array();
		foreach ($product_basic['data'] as $pb)
		{
			$result[] = array(
				0 => $pb['number'] . ' ' . $pb['product_basic_name'],
				'id' => $pb['product_basic_id'],
				'number' => $pb['number'],
				'budget_price' => $pb['last_purchase_price'] ? $pb['last_purchase_price'] : $pb['purchase_price'],
				'preferred_provider_id' => $pb['preferred_provider_id'],
				'preferred_provider_name' => $pb['preferred_provider_name'],
				'warning_quantity' => $pb['warning_quantity'],
				'safe_quantity' => $pb['safe_quantity'],
				'actual_quantity' => $pb['actual_quantity'],
				'sold_quantity' => $pb['sold_quantity'],
				'available_quantity' => $pb['available_quantity'],
				'purchase_budget_quantity' => $pb['purchase_budget_quantity'],
				'purchase_quantity' => $pb['purchase_quantity'],
				'wholesale_quantity' => $pb['wholesale_quantity'],
				'sales_status' =>  Helper_BSS_Normal::getIniOne('product_sales_status','value',$pb['sales_status'],'name'),
				'purchase_status' => Helper_BSS_Normal::getIniOne('product_purchase_status','value',$pb['purchase_status'],'name'),
				'purchase_price' => $pb['purchase_price']
			);
		}
		echo json_encode($result);
		exit;
	}
	
	function actionProvider()
	{
		$this->_view['title'] = '供应商请求ajax';
		$q = $_REQUEST['q'];
		$provider = Product_Provider::find('id like ? or name like ?', $q.'%', '%'.$q.'%')->asArray()->getAll();
		$result = array();
		foreach ($provider as $p)
		{
			$result[] = array(
				0 => $p['id'] . ' ' . $p['name'],
				'id' => $p['id']
			);
		}
		echo json_encode($result);
		exit;
	}
	
	function actionPrint()
	{
		$this->_view['title'] = '打印采购单';
		$ids = explode(',', $_GET['ids']);
		if ($ids)
		{
			$purchase_order = Purchase_Order::find('purchase_order.id in (?)', $ids)
			->joinLeft('user as a', 'name as make_user_name', 'a.id = purchase_order.make_user_id')
			->joinLeft('user as b', 'name as purchase_user_name', 'b.id = purchase_order.purchase_user_id')
			->joinLeft('user as c', 'name as purchase_audit_user_name', 'c.id = purchase_order.purchase_audit_user_id')
			->joinLeft('user as d', 'name as storage_audit_user_name', 'd.id = purchase_order.storage_audit_user_id')
			->asArray()->getAll();
			foreach ($purchase_order as &$p)
			{
				$item = Purchase_Order_Item::find('purchase_order_item.purchase_order_id=?', $p['id'])
					->joinLeft('product_basic', 'number, name as product_name', 'product_basic.id=purchase_order_item.product_basic_id')
					->joinLeft('product_provider as a', 'name as budget_provider_name', 'a.id=purchase_order_item.budget_provider_id')
					->joinLeft('product_provider as b', 'name as actual_provider_name', 'b.id=purchase_order_item.actual_provider_id')
					->asArray()->getAll();
				Helper_BSS_Normal::getProductImgUrl($item);
				$p['item'] = $item;
			}
			unset($p);
			if (isset($_GET['pic']))
			{
				$this->_viewname = 'printfigure';
			}
			$this->_view['purchase_order'] = $purchase_order;
		}
	}
	
	function actionDrawbackCreate()
	{
		$this->_view['title'] = '采购退货单创建';
		$user = Purchase_Order::getUser();
		$this->_view['user'] = $user['data'];
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
	}
	
	function actionDrawbackCreateSave()
	{
		$this->_view['title'] = '采购退货单创建（保存）';
		if ($_POST)
		{
			$item = isset($_POST['item']) ? $_POST['item'] : array();
			$tmp = array();
			foreach ($item as $k => $i)
			{
				if (array_key_exists($i['product_basic_id'], $tmp))
				{
					$item[$tmp[$i['product_basic_id']]]['actual_quantity'] += $i['actual_quantity'];
					unset($item[$k]);
				}
				else
				{
					$tmp[$i['product_basic_id']] = $k;
				}
			}
			$drawback = array(
				'purchase_time' => $_POST['purchase_time'],
				'purchase_user_id' => $_POST['purchase_user_id'],
				'payment_type' => $_POST['purchase_order_payment_type'],
				'warehouse_id' => $_POST['warehouse_id'],
				'notes' => trim($_POST['notes']),
				'item' => $item
			);
			$result = Purchase_Order::createDrawback($drawback);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('保存成功', '正在返回..', url('Purchase::Order/DrawbackList'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('保存失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
	
	function actionDrawbackList()
	{
		$this->_view['title'] = '采购退货单列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$user = Purchase_Order::getUser();
		$this->_view['user'] = $user['data'];
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
		$url_arr = Helper_BSS_Normal::buildCondition();
		$url_arr['limit'] = $user['ack'];
		$url_arr['type'] = Q::ini('custom_flag/purchase_order_type/drawback/value');
		$result = Purchase_Order::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$purchase_order = $result['data'];
			$this->_view['purchase_order'] = $purchase_order;
			$page = new Helper_BSS_Page($result['pagination'], url('Purchase::Order/DrawbackList', $url_arr));
			$this->_view['page'] = $page->getPage();
			$where = Purchase_Order::buildSearchWhere($url_arr);
			$this->_view['return_amount'] = QDB::getConn()->execute('select sum(actual_amount) from purchase_order where ' . $where)->fetchOne();
			$this->_view['return_quantity'] = QDB::getConn()->execute('select sum(purchase_order_item.actual_quantity) from purchase_order_item left join purchase_order on purchase_order.id=purchase_order_item.purchase_order_id where ' . $where)->fetchOne();
		}
	}
	
	function actionDrawbackEdit()
	{
		$this->_view['title'] = '采购退货单编辑';
		if ( ! empty($_GET['id']))
		{
			$purchase_order = Purchase_Order::find('purchase_order.id=? and purchase_order.type=? and purchase_order.status=?', $_GET['id'], Q::ini('custom_flag/purchase_order_type/drawback/value'), Q::ini('custom_flag/purchase_order_status/new/value'))
				->joinLeft('warehouse', 'warehouse.name as warehouse_name', 'warehouse.id=purchase_order.warehouse_id')
				->asArray()->getOne();
			if ($purchase_order)
			{
				$item = Purchase_Order_Item::find('purchase_order_item.purchase_order_id=?', $purchase_order['id'])
					->joinLeft('product_warehouse', 'available_quantity', 'product_warehouse.product_basic_id=purchase_order_item.product_basic_id and product_warehouse.warehouse_id=' . $purchase_order['warehouse_id'])
					->joinLeft('product_basic', 'number as product_number, name as product_name', 'product_basic.id=purchase_order_item.product_basic_id')
					->joinLeft('product_provider', 'name as actual_provider_name', 'product_provider.id=purchase_order_item.actual_provider_id')
					->asArray()->getAll();
				$this->_view['purchase_order'] = $purchase_order;
				$this->_view['item'] = $item;
				$user = Purchase_Order::getUser();
				$this->_view['user'] = $user['data'];
			}
			else
			{
				return $this->_redirectMessage('发生错误', '正在返回..', url('Purchase::Order/DrawbackList'), FAILURE);
			}
		}
		else
		{
			return $this->_redirect(url('Purchase::Order/DrawbackList'));
		}
	}
	
	function actionDrawbackEditSave()
	{
		$this->_view['title'] = '采购退货单编辑（保存）';
		if ($_POST)
		{
		
			$item = isset($_POST['item']) ? $_POST['item'] : array();
			$tmp = array();
			foreach ($item as $k => $i)
			{
				if (array_key_exists($i['product_basic_id'], $tmp))
				{
					$item[$tmp[$i['product_basic_id']]]['actual_quantity'] += $i['actual_quantity'];
					unset($item[$k]);
				}
				else
				{
					$tmp[$i['product_basic_id']] = $k;
				}
			}
			$drawback = array(
				'id' => $_POST['id'],
				'purchase_time' => $_POST['purchase_time'],	
				'purchase_user_id' => $_POST['purchase_user_id'],
				'payment_type' => $_POST['purchase_order_payment_type'],
				'notes' => trim($_POST['notes']),
				'item' => $item
			);
			$result = Purchase_Order::editDrawback($drawback);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('保存成功', '正在返回..', url('Purchase::Order/DrawbackList'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('保存失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
	
	function actionPrintProductBarcode()
	{
		$this->_view['title'] = '打印产品条形码';
		$ids = explode(',', $_GET['ids']);
		if ($ids)
		{
			$purchase_order = Purchase_Order::find('id in (?)', $ids)->asArray()->getAll();
			$item = array();
			foreach ($purchase_order as $p)
			{
				$purchase_order_item = Purchase_order_item::find('purchase_order_item.purchase_order_id=? and purchase_order_item.audit_flag=?', $p['id'], Q::ini('custom_flag/purchase_order_item_audit_flag/unaudited/value'))
					->joinLeft('product_basic', '', 'product_basic.id=purchase_order_item.product_basic_id')
					->joinLeft('product_warehouse', '', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $p['warehouse_id'])
					->joinLeft('product_material','', 'product_material.id=product_warehouse.product_material_id')
					->setColumns('product_basic.number, product_warehouse.shelf_position, product_warehouse.product_feature, purchase_order_item.actual_quantity as quantity, product_material.number as material_number')
					->asArray()->getAll();
				$item = array_merge($purchase_order_item, $item);
			}
			$item = Helper_BSS_Array::SortByValue($item, 'number', 'asc');
			OLM_Barcode::productNumber($item);
			exit;
		}
	}
	
	function actionMobileOrderList()
	{
		$this->_view['title'] = '列表（手机版）';
		$this->_view['current_user_id'] = CURRENT_USER_ID;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$this->_view['url'] = url('Purchase::Order/MobileOrderList', $url_arr);
		$url_arr['purchase_order_status'][Q::ini('custom_flag/purchase_order_status/purchasing/value')] = Q::ini('custom_flag/purchase_order_status/purchasing/value');
		$url_arr['type'] = Q::ini('custom_flag/purchase_order_type/order/value');
		$result = Purchase_Order::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$purchase_order = $result['data'];
			$this->_view['purchase_order'] = $purchase_order;
			$this->_view['page'] = $result['pagination'];
		}
	}
	
	function actionMobileDetail()
	{
		$this->_view['title'] = '详细（手机版）';
		$url_arr = Helper_BSS_Normal::buildCondition();
		if ($url_arr)
		{
			$purchase_order = Purchase_Order::find('purchase_order.id =?', $url_arr['id'])
				->joinLeft('user', 'name as purchase_user_name', 'user.id = purchase_order.purchase_user_id')
				->asArray()->getOne();
			$item = Purchase_Order_Item::find('purchase_order_item.purchase_order_id =?', $url_arr['id'])
				->joinLeft('product_basic', 'number as product_number, name', 'product_basic.id = purchase_order_item.product_basic_id')
				->joinLeft('product_warehouse', 'product_warehouse.purchase_budget_quantity', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $purchase_order['warehouse_id'])
				->joinLeft('product_provider as a', 'name as budget_provider_name', 'a.id = purchase_order_item.budget_provider_id')
				->joinLeft('product_provider as b', 'name as actual_provider_name', 'b.id = purchase_order_item.actual_provider_id')
				->asArray()->getAll();
			Helper_BSS_Normal::getProductImgUrl($item, 'product_number');
			$this->_view['purchase_order'] = $purchase_order;
			$this->_view['item'] = $item;
		}
		else
		{
			return $this->_redirect(url('Purchase::Order/MobileOrderList'));
		}
	}
	
	function actionUnhold()
	{
		$this->_view['title'] = '取消滞留';
		if ($this->_context->isGET())
		{
			$purchase_order_ids = explode(',', $_GET['ids']);
			$result = Purchase_order::changePurchaseHoldFlag($purchase_order_ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('取消滞留成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('取消部分失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
}